//
//  LogisticsViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/5/17.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "LogisticsViewController.h"
#import "LogistTableViewCell.h"
#import "HeadTableViewCell.h"
#import <CommonCrypto/CommonDigest.h>
@interface LogisticsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView  *tableView;
@property (nonatomic ,strong) NSDictionary *json;
@property (nonatomic ,strong) NSArray *logisArry;

@end

@implementation LogisticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"物流信息";
    self.json=[[NSDictionary alloc]init];
    self.logisArry=[[NSArray alloc]init];
    [self.view addSubview:[self tableView]];
    [self loadlogistResource];
    // Do any additional setup after loading the view.
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-64) style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.separatorInset=UIEdgeInsetsMake(0, 33, 0, 0);
        _tableView.separatorColor=SeparatorColor;
        _tableView.backgroundColor=Gray_Color;
        [_tableView registerNib:[UINib nibWithNibName:@"HeadTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"HeadCell"];
         [_tableView registerNib:[UINib nibWithNibName:@"LogistTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LogistCell"];
    }
    return _tableView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 20;
    }else{
        return 0.01;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 76;
    }else{
        CGFloat height=[ZJUITools getHeightByWidth:MainW-45 title:@"您的订单" font:FontAndStyle12];
        return height+35;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else{
        if (self.logisArry.count==0) {
            return 1;
        }else{
            return self.logisArry.count;
        }
        
    }
   
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        HeadTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"HeadCell"];
        [cell.shopImag sd_setImageWithURL:[NSURL URLWithString:self.imgUrl] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
        cell.numeber.text=[NSString stringWithFormat:@"订单号:%@",self.logisticCode];
        cell.kuaidi.text=[NSString stringWithFormat:@"国内承运人:%@",self.shipperName];
        if ([cell.numeber.text isEqualToString:@"订单号:(null)"]) {
            cell.numeber.text=[NSString stringWithFormat:@"订单号:暂无物流单号"];
        }
        if ([cell.kuaidi.text isEqualToString:@"国内承运人:(null)"]) {
            cell.kuaidi.text=[NSString stringWithFormat:@"国内承运人:暂无物流信息"];
        }
        return cell;
    }else{
        LogistTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LogistCell"];
        //cell.information.text=@"您的订单您的订单您的订单您的订单您的订单您的订单您的订单您的订单您的订单您的订单您的订单您的订单";
        if (indexPath.row==0) {
            cell.topLine.hidden=YES;
        }
        if (self.logisArry.count==0) {
            cell.information.text=self.json[@"Reason"];
            //cell.tlogisTime.text=
        }else{
            NSDictionary*dic=self.logisArry[indexPath.row];
            cell.information.text=dic[@"AcceptStation"];
            cell.tlogisTime.text=dic[@"AcceptTime"];
        }
        NSString *string = self.json[@"Reason"];
        // 5:行间距
        if (string.length!=0) {
            cell.information.attributedText = [self getAttributedStringWithString:string lineSpace:5];
        }
        return cell;
    }
    
}
-(NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; // 调整行间距
    NSRange range = NSMakeRange(0, [string length]);
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributedString;
}
-(void)loadlogistResource{
    //获取快递公司对应的编号
    NSString* shipperCode = self.shipperCode;
    //获取快递单号
    NSString* logisticCode = self.logisticCode;
    NSString* requestData = [NSString stringWithFormat:@"{\"OrderCode\":\"%@\",\"ShipperCode\":\"%@\",\"LogisticCode\":\"%@\"}",self.orderSn,shipperCode,logisticCode];
    NSMutableDictionary* params = [[NSMutableDictionary alloc]init];
    NSString* dataSignTmp = [[NSString alloc]initWithFormat:@"%@%@",requestData,@"b0707ee4-ebbb-481d-b179-2971fb008129"];
    //这里使用到了MD5加密程序，以及Base64编码
    NSString* dataSign = [self base64EncodingWithData: [[self md5:dataSignTmp] dataUsingEncoding:NSUTF8StringEncoding]];
    [params setObject:[requestData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"RequestData"];
    [params setObject:@"1288483" forKey:@"EBusinessID"];
    [params setObject:@"1002" forKey:@"RequestType"];
    [params setObject:[dataSign stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:@"DataSign"];
    [params setObject:@"2" forKey:@"DataType"];
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:@"http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
         //NSLog(@"请求成功：%@",json);
        self.json=json;
        NSMutableArray *array =json[@"Traces"];
        self.logisArry = [[array reverseObjectEnumerator] allObjects];
        [self.tableView reloadData];
        //3. 获得网络数据赋值给ExpressInfo对象
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"请求失败：%@",error.description);
    }];
}
- (NSString *) md5:(NSString *) input {
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}
-(NSString *)base64EncodingWithData:(NSData *)sourceData{
    if (!sourceData) {//如果sourceData则返回nil，不进行加密。
        return nil;
    }
    NSString *resultString = [sourceData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return resultString;
}

@end
